package think.bank;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

public class BankServices {
	private static ServerSocket server;
	private static Bank bank;
	private static String accoutName = null;
	static{
		//自动实例化银行账号信息
		IndividualAccount iAccout = new IndividualAccount("tqq",2000);
		IndividualAccount iAccout2 = new IndividualAccount("yyy",3000);
		bank = Bank.getInstance();
		bank.createAccount(iAccout);
		bank.createAccount(iAccout2);
	}
	
	public static void init() throws IOException {
		getServer(); 
		while (true) {
			Socket soc = server.accept();
			System.out.println(soc.getLocalAddress() + " 已连接...");
			try (
					// 获取socket输入
					BufferedReader reader = new BufferedReader(new InputStreamReader(soc.getInputStream()));
					// 获取socket输出
					PrintWriter pw = new PrintWriter(soc.getOutputStream());) {
				while (true) {
					String request = reader.readLine();
					String response = "无返回" ;
					
					response = dispose(request);
					
					//System.out.println("服务器接受信息: " + request);
					pw.println(response);
					pw.flush();
					//System.out.println("服务器返回信息: " + response);
					
					if ("over".equals(request)) {
						System.out.println("服务关闭...");
						break;
					}
				}
			}
		}
	}
	
	public static String dispose(String request){
		
		Map<String,IndividualAccount> account = bank.getAccount();

		if(accoutName!=null){
			if("取钱".equals(request)){
				bank.getMoney(accoutName, 100);
				return  "操作成功";
			}
			if("查询".equals(request)){
				int money = account.get(accoutName).getAccount();
				return  "余额 : " + money;
			}
			return "请输入操作";
		}
		if(account.containsKey(request)){
			accoutName = request;
			return   "请输入操作";
		}
		
		return   "请输入账户名";
		
	}
/*	public void draw(String name){
		//Code code  = Code.FAIL;
		switch(name){
		case "取钱" : bank.getMoney(account, money); 
		default:
			break;
		
		}
	}*/
	
	
	public  static ServerSocket getServer() throws IOException{
		if(server==null){
			server = new ServerSocket(8686);
		 }
		return server;
	}
	public static void closeServer() throws IOException{
		if(server!=null){
			server.close();
		}
	}
	
	public static void main(String[] args) throws IOException {
		BankServices.init();
	}
}
